import requests
import warnings
import time
from datetime import datetime
from utils import close_qemu, read_config
import sys

def try_web_access(host_ip, port):
    url = "https://{host_ip}:{port}/UI/Rest/Login".format(host_ip=host_ip, port=port)
    retcode = -1
    session = requests.Session()
    session.trust_env = False
    try:
        with warnings.catch_warnings():
            warnings.simplefilter(
                "ignore", category=requests.packages.urllib3.exceptions.InsecureRequestWarning)
            response = session.get(url, timeout=10, proxies={}, verify=False)
            retcode = response.status_code
    except requests.exceptions.RequestException as e:
        pass
    return retcode == 200

def try_redfish_access(host_ip, port):
    url = "https://{host_ip}:{port}/redfish/v1".format(host_ip=host_ip, port=port)
    retcode = -1
    session = requests.Session()
    session.trust_env = False
    try:
        with warnings.catch_warnings():
            warnings.simplefilter(
                'ignore', category = requests.packages.urllib3.exceptions.InsecureRequestWarning
            )
            response = session.get(url, timeout=10, proxies={}, verify=False)
            retcode = response.status_code
            if retcode == 200 and "Redfish" in response.text:
                return True
    except requests.exceptions.RequestException as e:
        pass
    
    return retcode == 200

def execute(host_ip):
    web_status = False
    redfish_status = False
    config = read_config()
    web_port = config['mapports']['https']
    print(web_port)
    print("正在连接bmc...")

    start_time = datetime.now()
    while not (web_status and redfish_status):
        end_time = datetime.now()
        elapsed = (end_time - start_time).total_seconds()
        if elapsed >= 600:
            print("❌ 连接bmc超时(10分钟)...")
            close_qemu()
            exit(1)
        web_status = try_web_access(host_ip, web_port)
        if web_status:
            redfish_status = try_redfish_access(host_ip, web_port)
        sys.stdout.write(f"\r等待服务就绪: Web [{'√' if web_status else 'X'}] | Redfish [{'√' if redfish_status else 'X'}] | 已等待 {int(elapsed)}seconds")
        time.sleep(0.5 if not (web_status and redfish_status) else 0)
    print("✅ 连接bmc成功!")
    time.sleep(30)


if __name__ == "__main__":
    # 支持传入参数 --HOST_IP
    host_ip = "127.0.0.1"
    for i, arg in enumerate(sys.argv):
        if arg == "--HOST_IP" and i + 1 < len(sys.argv):
            host_ip = sys.argv[i + 1]
    execute(host_ip)
